package com.dandelion.api.controller;

import com.dandelion.api.domain.OrderAdapterVO;
import com.dandelion.api.domain.OrderCreationResult;
import com.dandelion.api.domain.OrderListItemAdapter;
import com.dandelion.api.domain.OrderSearchResult;
import com.dandelion.api.manager.UserOrderManager;
import com.dandelion.api.request.OrderRequest;
import com.dandelion.common.dao.auto.pojo.Order;
import com.dandelion.common.http.HttpContext;
import com.dandelion.common.utils.ApiArgs;
import com.rockit.core.pojo.JsonResult;
import com.rockit.core.utils.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user/order")
public class UserOrderController extends BaseRestController {
    @Autowired
    private UserOrderManager userOrderManager;

    @RequestMapping("/query/mobile/cancelled")
    public JsonResult queryCancelledOrderByMobile(String mobile) {
        Assert.hasText(mobile, "mobile is required");
        List<OrderListItemAdapter> vo = userOrderManager.getCancelledOrderListByMobile(mobile);
        return ok(vo);
    }

    @RequestMapping("/query/mobile/finished")
    public JsonResult queryFinishedOrderByMobile(String mobile) {
        Assert.hasText(mobile, "mobile is required");
        List<OrderListItemAdapter> vo = userOrderManager.getFinishedOrderListByMobile(mobile);
        return ok(vo);
    }

    @RequestMapping("/query/mobile/processing")
    public JsonResult queryProcessingOrderByMobile(String mobile) {
        Assert.hasText(mobile, "mobile is required");
        List<OrderListItemAdapter> vo = userOrderManager.getProcessingOrderListByMobile(mobile);
        return ok(vo);
    }

    @RequestMapping("/query/my/finished")
    public JsonResult queryFinishedMyOrder() {
        long userId = HttpContext.current().getRequireUserId();
        List<OrderListItemAdapter> vo = userOrderManager.getFinishedMyOrderList(userId);
        return ok(vo);
    }

    @RequestMapping("/query/my/cancelled")
    public JsonResult queryCancelledMyOrder() {
        long userId = HttpContext.current().getRequireUserId();
        List<OrderListItemAdapter> vo = userOrderManager.getCancelledMyOrderList(userId);
        return ok(vo);
    }

    @RequestMapping("/query/my/processing")
    public JsonResult queryProcessingMyOrder() {
        long userId = HttpContext.current().getRequireUserId();
        List<OrderListItemAdapter> vo = userOrderManager.getProcessingMyOrderList(userId);
        return ok(vo);
    }

    @RequestMapping("/detail")
    public JsonResult queryOrderByNo(String orderNo) {
        Assert.hasText(orderNo, "orderNo is required");
        OrderAdapterVO vo = userOrderManager.queryOrderByNo(orderNo);
        return ok(vo);
    }

    @RequestMapping("/detail/simple")
    public JsonResult queryOrderByNoSimple(String orderNo) {
        Assert.hasText(orderNo, "orderNo is required");
        OrderSearchResult result = userOrderManager.searchByOrderNo(orderNo);
        return ok(result);
    }

    @RequestMapping("/create")
    public JsonResult createNewOrder(String data) {
        Assert.hasText(data, "data is required");
        OrderRequest request = JacksonUtil.toObject(data, OrderRequest.class);
        //OrderRequest request = mockRequest();
        if (request == null) {
            throw new IllegalArgumentException("parameter 'data' is invalid json");
        }
        checkOrderRequest(request);
        long userId = HttpContext.current().getUserId();
        Order order = userOrderManager.createNewOrder(userId, request);
        OrderCreationResult result = new OrderCreationResult();
        result.setOrderNo(order.getOrderNo());
        return ok(result);
    }

    private void checkOrderRequest(OrderRequest request) {
        ApiArgs.notBlankAndLenLessThan("orderCctName", request.getOrderCctName(), 16);
        ApiArgs.notBlankAndLenLessThan("orderCctMobile", request.getOrderCctMobile(), 32);
        ApiArgs.legalIntId("topCatId", request.getTopCatId());
        ApiArgs.legalIntId("svrId", request.getSvrId());
        ApiArgs.notBlankAndLenLessThan("cstName", request.getCstName(), 16);
        ApiArgs.notBlankAndLenLessThan("cstMobile", request.getCstMobile(), 32);
        ApiArgs.notBlankAndLenLessThan("cstAddrProvCode", request.getCstAddrProvCode(), 16);
        ApiArgs.notBlankAndLenLessThan("cstAddrCityCode", request.getCstAddrCityCode(), 16);
        ApiArgs.notBlankAndLenLessThan("cstAddrAreaCode", request.getCstAddrAreaCode(), 16);
        ApiArgs.lenLessThan("cstAddrDistCode", request.getCstAddrDistCode(), 16);
        ApiArgs.notBlankAndLenLessThan("cstAddrDetail", request.getCstAddrDetail(), 64);
        request.setBldLift(ApiArgs.normalizeByteBool(request.getBldLift()));
        ApiArgs.lenLessThan("bldFloor", request.getBldFloor(), 8);
        request.setExprStatus(ApiArgs.normalizeByteBool(request.getExprStatus()));
        ApiArgs.lenLessThan("exprOrderNo", request.getExprOrderNo(), 32);
        ApiArgs.lenLessThan("pkCctName", request.getBldFloor(), 8);
        ApiArgs.lenLessThan("pkCctMobile", request.getPkCctMobile(), 32);
        ApiArgs.lenLessThan("pkAddr", request.getPkAddr(), 128);
        ApiArgs.lenLessThan("verifyCode", request.getVerifyCode(), 128);
        ApiArgs.lenLessThan("cstExpectDeliverDate", request.getCstExpectDeliverDate(), 16);
        ApiArgs.lenLessThan("estDeliverDate", request.getEstDeliverDate(), 16);
        request.setPreFrPay(ApiArgs.normalizeByteBool(request.getPreFrPay()));
        ApiArgs.lenLessThan("specialReq", request.getSpecialReq(), 1024);
//        ApiArgs.notEmpty("items", request.getItems());

        if (CollectionUtils.isEmpty(request.getItems())) {
            return;
        }

        request.getItems().stream().forEach(item -> {
            ApiArgs.legalIntId("item.subCatId", item.getSubCatId());
//            ApiArgs.legalIntId("item.subCatId", item.getSubCatId());
            ApiArgs.lenLessThan("item.img", item.getImg(), 256);
            ApiArgs.lenLessThan("item.model", item.getModel(), 32);
            ApiArgs.lenLessThan("item.req", item.getModel(), 256);
        });
    }

    @RequestMapping("/cancel")
    public JsonResult cancelOrder(String orderNo) {
        Assert.hasText(orderNo, "data is required");
        long userId = HttpContext.current().getRequireUserId();
        userOrderManager.cancelOrder(userId, orderNo);
        return ok();
    }

//    private OrderRequest mockRequest() {
//        OrderRequest o = new OrderRequest();
//
//        o.setOrderCctName("Allen");
//        o.setOrderCctMobile("13450354030");
//
//        o.setTopCatId(1);
//        o.setSvrId(1);
//
//        o.setCstName("李文");
//        o.setCstMobile("13450398271");
//        o.setCstAddrProvCode("101101");
//        o.setCstAddrCityCode("101101101105");
//        o.setCstAddrAreaCode("911101105120");
//        o.setCstAddrDistCode("xxx街道xxx号");
//        o.setBldLift((byte) 1);
//        o.setBldFloor("5f");
//        o.setVerify((byte) 1);
//
//        o.setExprStatus((byte) 1);
//        o.setExprComId(1);
//        o.setExprOrderNo("23049348");
//        o.setPkCctName("张三");
//        o.setPkCctMobile("18729384823");
//        o.setPkAddr("xxxxxxxxxxxx");
//        o.setPkgNum(4);
//        o.setPreFrPay((byte) 0);
//
//        o.setSpecialReq("啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
//
//        o.setItems(mockOrderGoodsItems());
//        return o;
//    }

    private List<OrderRequest.OrderGoodsItemRequest> mockOrderGoodsItems() {
        List<OrderRequest.OrderGoodsItemRequest> items = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            OrderRequest.OrderGoodsItemRequest item = new OrderRequest.OrderGoodsItemRequest();
            item.setSubCatId(1);
            item.setLeafCatId(3);
            item.setImg("http://baidu.com/" + i + ".jpg");
            item.setModel("xxx型号-" + i);
            item.setWeight(new BigDecimal(1002.2));
            item.setHeight(10 * i);
            item.setLength(60 * i);
            item.setWidth(80 * i);
            item.setItemNum(i + 3);
            item.setReq("nanannana");
            items.add(item);
        }
        return items;
    }
}
